/*
 * @(#)MD5.java Mar 31, 2008
 * 
 * Copyright 2007 by ChinanetCenter Corporation.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ChinanetCenter Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with ChinanetCenter.
 * 
 */
package com.cnc.fd.util;

import java.io.File;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

/**
 * @author 阿闲
 * @date   Mar 31, 2008
 * @version 1.0
 */
public class MsgDigest {

	/**
	 * 获取某个字符串的md5
	 * @param s
	 * @return
	 */
	public final static String md5(String str) {
	
		try {
		
			MessageDigest md = MessageDigest.getInstance("MD5");
			
			md.update(str.getBytes());
			
			return getMd5String(md.digest());			

		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取某个文件的md5
	 * @param file
	 * @return
	 */
	public final static String md5(File file) {

		
		try {

			MessageDigest md = MessageDigest.getInstance("MD5");

			DigestInputStream in = new DigestInputStream(new FileInputStream(
					file), md);
			
			byte[] buffer = new byte[8192];
			
			while(in.read(buffer) != -1)
				;			

			return getMd5String(md.digest());

		} catch (Exception e) {
			return null;
		}
	}
	
	private static String getMd5String(byte[] bytes){
		
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		
		int j = bytes.length;
		
		char str[] = new char[j * 2];		
		
		for (int i = 0, k=0; i < j; i++) {
			byte byte0 = bytes[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}

		return new String(str);
	}
}
